import pinecone
from pinecone import Pinecone, ServerlessSpec

pinecone = Pinecone(api_key="pcsk_4tZGoM_HLqw5naiHZaXJWLh4WY3W3MEEcozbMT5Ci3cUkYpTGSJXNdLZZWzUQyZcyp9MVp")
index_name = "mnist-index"

existing_indexes = pinecone.list_indexes()

if any(index['name'] == index_name for index in existing_indexes):
    print(f"Index '{index_name}' already exists, deleting...")
    pinecone.delete_index(index_name)
    print(f"Index '{index_name}' has been successfully deleted.")
else:
    print(f"Index '{index_name}' does not exist, will create a new index.")

index_name = "mnist-index"

print(f"Creating new index '{index_name}'...")
pinecone.create_index(
    name=index_name,
    dimension=64,
    metric="euclidean",
    spec=ServerlessSpec(
        cloud="aws",
        region="us-east-1"
    )
)
print(f"Index '{index_name}' created successfully.")

index = pinecone.Index(index_name)
print(f"Successfully connected to index '{index_name}'.")

[
    {
        "name": "mnist-index",
        "dimension": 64,
        "metric": "euclidean",
        "host": "mnist-index-il86agr.svc.aped-4627-b74a.pinecone.io",
        "spec": {
            "serverless": {
                "cloud": "aws",
                "region": "us-east-1"
            }
        },
        "status": {
            "ready": True,
            "state": "Ready"
        },
        "deletion_protection": "disabled"
    }
]

from sklearn.datasets import load_digits

digits = load_digits(n_class=10)

X = digits.data
y = digits.target

vectors = []

for i in range(len(X)):
    vector_id = str(i)
    vector_values = X[i].tolist()
    metadata = {"label": int(y[i])}
    vectors.append((vector_id, vector_values, metadata))

batch_size = 1000

for i in range(0, len(vectors), batch_size):
    batch = vectors[i:i + batch_size]
    index.upsert(batch)

import matplotlib.pyplot as plt
import numpy as np
from collections import Counter

digit_3 = np.array(
    [
        [0, 0, 255, 255, 255, 255, 0, 0],
        [0, 0, 0, 0, 0, 255, 0, 0],
        [0, 0, 0, 0, 0, 255, 0, 0],
        [0, 0, 0, 255, 255, 255, 0, 0],
        [0, 0, 0, 0, 0, 255, 0, 0],
        [0, 0, 0, 0, 0, 255, 0, 0],
        [0, 0, 0, 0, 0, 255, 0, 0],
        [0, 0, 255, 255, 255, 255, 0, 0]
    ]
)

digit_3_flatten = (digit_3 / 255.0) * 16
query_data = digit_3_flatten.ravel().tolist()

results = index.query(
    vector=query_data,
    top_k=11,
    include_metadata=True
)

labels = [match['metadata']['label'] for match in results['matches']]

for match, label in zip(results['matches'], labels):
    print(f"id: {match['id']}, distance: {match['score']}, label: {label}")

final_prediction = Counter(labels).most_common(1)[0][0] if labels else 3

plt.imshow(digit_3, cmap='gray')
plt.title(f"Predicted digit: {final_prediction}", size=15)
plt.axis('off')
plt.show()